package com.fang.excel.service;

import com.fang.excel.entity.UserInformation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class AsyncImportService {

    @Autowired
    private UserInformationService userInformationService;

    public void importData(List<UserInformation> dataList) {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        log.info("当前线程核数："+Runtime.getRuntime().availableProcessors());
        List<List<UserInformation>> partitions = partitionList(dataList, 10000); // 批量大小设置为1000
        Instant start = Instant.now();
        log.info("====================开始执行插入操作======================");
        for (List<UserInformation> partition : partitions) {
            executorService.submit(() -> userInformationService.getBaseMapper().batchInsert(partition));
        }

        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }

        Instant end = Instant.now();
        // 计算时间差
        Duration timeElapsed = Duration.between(start, end);
        log.info("==============>操作耗时: " + timeElapsed.toMillis() + " 毫秒.");
    }

    private <T> List<List<T>> partitionList(List<T> list, int size) {
        List<List<T>> partitions = new ArrayList<>();
        for (int i = 0; i < list.size(); i += size) {
            partitions.add(new ArrayList<>(list.subList(i, Math.min(i + size, list.size()))));
        }
        return partitions;
    }
}
